/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import entitas.User;
import entitas.DaftarUser;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Rido
 */
public class LogicUser {

    HttpServletRequest request;

    public LogicUser(HttpServletRequest request) {
        this.request = request;
    }

    /* method untuk melakukan fungsi input user, yaitu mengambil nilai textfield pada form user
     * untuk kemudian dimasukkan sebagai nilai untuk membuat baris baru pada tabel user
     */
    public String inputUser() {
        User user = new User();
        DaftarUser du = new DaftarUser();

        String username = request.getParameter("username");
        String namaLengkap = request.getParameter("namalengkap");
        String email = request.getParameter("email");
        String password = request.getParameter("password");


        if (username.equals("") || namaLengkap.equals("") || email.equals("")
                || password.equals("")) {
            return "errorIDusersama.jsp";
        } else {
            boolean hasilCheck = du.checkUser(username);
            if (!hasilCheck) {
                user.setUsername(username);
                user.setNamaLengkap(namaLengkap);
                user.setEmail(email);
                user.setPassword(password);

                du.createUser(user);
                return "index.jsp";
            } else {
                return "error2.jsp";
            }
        }
    }

    public String lihatUser() {
        List<User> user = new ArrayList<User>();
        DaftarUser du = new DaftarUser();

        user = du.getUsers();
        request.setAttribute("users", user);
        return "daftarUser.jsp";

    }

    public String loggedIn() {
        HttpSession session = request.getSession();
        User user = new User();
        DaftarUser du = new DaftarUser();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        boolean hasil = du.checkUser(username);
        if (hasil) {
            user = null;
            user = du.getUser(username);
            if (username.equals(user.getUsername()) && password.equals(user.getPassword())) {
                session.setAttribute("username", user);
                return "index.jsp";
            } else {
                return "loginForm.jsp";
            }
        }else{
            return "loginForm.jsp";
        }


    }
}
